package com.fourpigeon.utils;

import cn.hutool.core.bean.BeanUtil;
import com.fourpigeon.domain.UserDTO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.fourpigeon.utils.RedisConstants.LOGIN_USER_TOKEN_KEY;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;

    public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

//    @Deprecated
//    public boolean preHandle1(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        //获取请求头中的token
//        String token = request.getHeader("authorization");
//        //不存在，设置401状态码，拦截
//        if (token == null) {
//            response.setStatus(401);
//            return false;
//        }
//        //查询Redis中的token信息
//        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(LOGIN_USER_TOKEN_KEY+token);
//        if (userMap.isEmpty()) {
//            //不存在，拦截
//            response.setStatus(401);
//            return false;
//        }
//        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
//        //保存到ThreadLocal
//        UserHolder.saveUser(userDTO);
//        //刷新token
//        stringRedisTemplate.expire(LOGIN_USER_TOKEN_KEY+token,30, TimeUnit.MINUTES);
//        //放行
//        return true;
//    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断在刷新token的拦截器中是否得到用户数据
        if (UserHolder.getUser()==null) {
            //状态码设置
            response.setStatus(401);
            return false;
        }
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        UserHolder.removeUser();
    }
}
